package com.leeyu.kafka.simple;

import org.apache.kafka.clients.producer.KafkaProducer;
import org.apache.kafka.clients.producer.ProducerRecord;
import org.apache.kafka.common.serialization.StringSerializer;

import java.util.Properties;

public class HelloKafkaProducer {

    public static void main(String[] args) {
        // 设置属性
        Properties properties = new Properties();
        // 连接地址
        properties.put("bootstrap.servers", "localhost:9092");
        // key value序列化
        properties.put("key.serializer", StringSerializer.class);
        properties.put("value.serializer", StringSerializer.class);

        // 构建Kafka生产者对象
        KafkaProducer<String, String> producer = new KafkaProducer<>(properties);
        try {
            ProducerRecord<String, String> record;
            try {
                // 构建消息
                record = new ProducerRecord<>("topic1", "key1", "value2");
                producer.send(record);
                System.out.println("发送消息成功！");
            } catch (Exception e) {
                System.out.println("发送消息失败！");
                e.printStackTrace();
            }
        } finally {
            producer.close();
        }
    }
}
